package com.karson.common.util;

import com.karson.common.model.StorageConfig;
import com.karson.common.response.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class AsmrUtil {

    /**
     * 根据长度生成随机数字
     * @param start 起始数字
     * @param end 结束数字
     * @return 生成的随机码
     */
    public static Integer randomCount(Integer start, Integer end){
        return (int)(Math.random()*(end - start +1) + start);
    }

    /**
     * 唯一id生成
     * @param uid
     * @param entityType
     * @param entityId
     * @return
     */
    public static long generateId(long uid, int entityType, int entityId) {
        // 给 type+entityId 预留 8 位
        return uid * 1_000_000_0000L
                + (long) entityType * 100_000L
                + entityId;
    }
    /**
     * 从请求中获取存储类型（示例：从请求头获取）
     * @param request HTTP 请求对象
     * @return 存储类型（"MINIO" 或 "LOCAL"）
     */
    public static String getStorageTypeFromRequest(HttpServletRequest request) {
        String storageType = request.getHeader("Storage-Type");
        if (storageType == null || storageType.trim().isEmpty()) {
            storageType = StorageConfig.LOCAL; // 默认值
        }
        return storageType;
    }

    public static String getClientIp(HttpServletRequest request){
        String ip = request.getHeader("X-Forwarded-For");
        if(checkIsIp(ip)){
            return ip;
        }

        ip = request.getHeader("X-Real-IP");
        if(checkIsIp(ip)){
            return ip;
        }

        ip = request.getRemoteAddr();
        if("0:0:0:0:0:0:0:1".equals(ip)){
            //本地 localhost访问 ipv6
            ip = "127.0.0.1";
        }
        if(checkIsIp(ip)){
            return ip;
        }

        return "";
    }
    public static boolean fileValid(MultipartFile file,Integer fileType) throws IOException {
        if (file == null || file.getBytes().length == 0) {
            return false;
        }
        String filename = file.getOriginalFilename();
        if (fileType != null) {
            String fileTypeExists = FileTypeUtil.isFileTypeExists(fileType, filename);
            return fileTypeExists == null;
        }
        return true;
    }

    /**
     * 检测是否为ip
     * @param ip 参数
     * @author Mr.Zhang
     * @since 2020-04-22
     * @return String
     */
    public static boolean checkIsIp(String ip){
        if(StringUtils.isBlank(ip)){
            return false;
        }

        if("unKnown".equals(ip)){
            return false;
        }

        if("unknown".equals(ip)){
            return false;
        }

        return ip.split("\\.").length == 4;
    }

    /**
     * 获取uuid
     * @author Mr.Zhang
     * @since 2020-05-06
     * @
     */
    public static String getUuid(){
        return UUID.randomUUID().toString().replace("-", "");
    }


    public static List<String> stringToArrayStr(String str){
        return stringToArrayStrRegex(str, ",");
    }
    /**
     * 字符串分割，转化为数组
     * @param str 字符串
     * @param regex 分隔符有
     * @author Mr.Zhang
     * @since 2020-04-22
     * @return List<String>
     */
    public static List<String> stringToArrayStrRegex(String str, String regex ){
        List<String> list = new ArrayList<>();
        if (str.contains(regex)){

            String[] split = str.split(regex);

            for (String value : split) {
                if(!StringUtils.isBlank(value)){
                    list.add(value);
                }
            }
        }else {
            list.add(str);
        }
        return list;
    }

    /**
     * 数组转字符串去除中括号
     * @param arr
     * @return
     */
    public static <T> String arrayToStringNoBrackets(List<T> arr) {
        if (arr == null || arr.isEmpty()) {
            return "";
        }
        return arr.toString().replaceAll("[\\[\\]]", "");
    }
}
